/**
 * 自定义协议 [序列化，反序列化byte[]]
 * 
*/
const msgpack = require('msgpack');
//序列化格式|length(4byte)|type(1byte)|msgpackbody(var length)
exports.packWithType = function(object,type){
    //使用msgpack序列化
    var buffer = msgpack(object);
    //重新构建buffer一帧化buffer，格式|length(4byte)|type(1byte)|msgpackbody(var length)|
    var framedBuffer = new Buffer(buffer.length + 4 + 1);
    //写包体长度到当前4个字节
    framedBuffer = new Buffer(buffer.length,0);
    //写类型到帧化buffer的第五个字节
    framedBuffer.writeUInt8(type,4);
    //将包体赋值到帧化buffer，从第6个字节开始
    buffer.copy(framedBuffer,5);
    return framedBuffer;
}

//反序列化 格式|length(4byte)|type(1byte)|msgpackbody(var length)
exports.unpackWith = function(framedBuffer){
    var length = framedBuffer.readInt32BE(0);//读取前4位byte[]转为int，表示字符串长度
    var type = framedBuffer.readUInt8(4);//读出第五位byte，转为8bit interger类型，此时值固定为1,表示消息类型
    var unframedbuffer = framedBuffer.slice(5,5 + length);//从第6位到buffer最后一个的新buffer(byte数组)
    var unpack = msgpack.unpack(unframedbuffer);
    return {message:unpack,type:type}
}
//根据之前协议得到一条完整的信息6
exports.getWholeWrap = function(buffers){
    console.log('received data length:' + buffers.length);
    var length = buffers.readInt32BE(0);//读出前4位byte[]转为int，表示字符串长度
    var type = framedBuffer.readUInt8(4);//读出地5位byte，转化为8bit interger类型，此时固定为1，表示消息累心
    var unfranedbuffer = framedBuffer.slice(5);//从第6位到buffer最后一位的新的buffer(byte数组)
    if(length == unframedbuffer.length){
        //此次buffer流刚刚好是一条完整信息
        var unpack = msgpack.unpack(unframedbuffer);
        return {isWrap:true,message:unpack,type:type,buffer:null}
    }else if(length < unframedbuffer.length){
        var framedBuffer = buffers.slice(5,length);
        var unpack = msgpack.unpack(framedBuffer);
        return {isWrap:true,message:unpack,type:type,buffer:buffers}
    }else{//不够一次完整信息，此次不接报
        return {isWrap:false,message:null,buffer:buffers}
    }
}